package com.jike.noobmoney.mvp.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.image.imagepicker.ImagePicker;
import com.image.imagepicker.bean.ImageItem;
import com.image.imagepicker.ui.ImageGridActivity;
import com.image.imagepicker.ui.ImagePreviewDelActivity;
import com.jike.noobmoney.R;
import com.jike.noobmoney.adapter.ImagePickerAdapter;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.entity.BuzhouEntity;
import com.jike.noobmoney.entity.CateListEntity;
import com.jike.noobmoney.entity.MoneyEntity;
import com.jike.noobmoney.helper.ImageLoader;
import com.jike.noobmoney.mvp.presenter.AppPresenter;
import com.jike.noobmoney.mvp.presenter.TaskPresenter;
import com.jike.noobmoney.mvp.presenter.UserPresenter;
import com.jike.noobmoney.mvp.view.widget.PushDialog;
import com.jike.noobmoney.mvp.view.widget.TaskTypeDialog;
import com.jike.noobmoney.net.IView;
import com.jike.noobmoney.util.AppUtils;
import com.jike.noobmoney.util.ComUtils;
import com.jike.noobmoney.util.Logger;
import com.jike.noobmoney.util.SPUtils;
import com.jike.noobmoney.util.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by kekex on 2019/3/19.
 * 发布任务
 */

public class PushTaskActivity extends BaseActivity implements IView, ImagePickerAdapter.OnRecyclerViewItemClickListener {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;


    public static final int IMAGE_ITEM_ADD = -1;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_type_title)
    TextView tvTypeTitle;
    @BindView(R.id.rl_task_type)
    RelativeLayout rlTaskType;

    @BindView(R.id.et_danjia)
    EditText etDanjia;
    @BindView(R.id.et_shuliang)
    EditText etShuliang;
    @BindView(R.id.tv_total)
    TextView tvTotal;
    @BindView(R.id.tv_need_chongzhi)
    TextView tvNeedChongzhi;
    @BindView(R.id.et_info)
    EditText etInfo;
    @BindView(R.id.et_taskname)
    EditText etTaskName;
    @BindView(R.id.tv_chongzhi)
    TextView tvChongzhi;
    @BindView(R.id.tv_fabu)
    TextView tvFabu;
    @BindView(R.id.ck_zhiding)
    ImageView ckZhiding;
    @BindView(R.id.tv_ecode)
    TextView tvEcode;
    @BindView(R.id.tv_lianjie)
    TextView tvLianjie;
    @BindView(R.id.iv_pic)
    ImageView ivPic;
    @BindView(R.id.et_lianjie)
    EditText etLianjie;
    @BindView(R.id.ll_view)
    LinearLayout llView;
    @BindView(R.id.iv_jiantou)
    ImageView ivJiantou;

    private int maxImgCount = 9;               //允许选择图片最大数
    private ArrayList<ImageItem> selImageList = new ArrayList<>(); //当前选择的所有图片
    public static final int REQUEST_CODE_PREVIEW = 101;
    public static final int REQUEST_CODE_SELECT = 100;

    private TaskPresenter taskPresenter;
    private List<CateListEntity.CatelistBean> mData = new ArrayList<>();
    private ImagePickerAdapter adapter;
    private AppPresenter appPresenter;
    private int typePostion = 0;
    private UserPresenter userPresenter;
    private String userid;
    private double money;
    private int c_id = 1;
    private boolean iszhiding = false;
    private int zhidingNum = 0;
    private String step = "";
    private String opentype = "";
    private String openurl = "";
    private String imageurl = "";
    private ImageView image;
    private String type;
    private boolean isGuanfang = false;
    private String t_id="0";


    @Override
    protected int layoutResID() {
        return R.layout.activity_push_task_new;
    }

    @Override
    protected void initData() {
        tvTitle.setText("发布任务");
        userPresenter = new UserPresenter(this);  //获取余额
        taskPresenter = new TaskPresenter(this);  //发布任务
        appPresenter = new AppPresenter(this);    //上传图片

        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);

        etDanjia.addTextChangedListener(new TextWatch(1));
        etShuliang.addTextChangedListener(new TextWatch(2));

        //获取余额
        getMoney();

        setZhiding(iszhiding);

        refreshType(true);

        View view1 = getView();
        addView(view1);
        addEvent(view1);

        Intent intent = getIntent();
        if (intent != null) {
            type = intent.getStringExtra("type");
        }

        if ("guanfang".equals(type)) {
            isGuanfang = true;
            tvTypeTitle.setText("官方推荐");
            ivJiantou.setVisibility(View.GONE);
        }else {
            getTaskType();
        }
    }

    View xkview;

    private void addEvent(View view) {
        TextView tvRemoveView = (TextView) view.findViewById(R.id.tv_remove_view);
        TextView tvAddView = (TextView) view.findViewById(R.id.tv_add_view);
        ImageView ivPic = (ImageView) view.findViewById(R.id.iv_pic);

        tvRemoveView.setOnClickListener(v -> {
            if (llView.getChildCount() == 1) {
                ToastUtils.showShortToastSafe("至少需要添加1步");
                return;
            }
            removeView(view);
        });

        tvAddView.setOnClickListener(v -> {
            if (llView.getChildCount() > 3) {
                ToastUtils.showShortToastSafe("最多只能添加4步");
                return;
            }

            View view2 = getView();
            addView(view2);
            addEvent(view2);
        });

        ivPic.setOnClickListener(v -> {
            xkview = v;
            ImagePicker.getInstance().setSelectLimit(1);
            ImagePicker.getInstance().setCrop(false);
            ImagePicker.getInstance().setShowCamera(true);
            ImagePicker.getInstance().setMultiMode(true);
            Intent intent1 = new Intent(context, ImageGridActivity.class);
            startActivityForResult(intent1, 1110);
        });
    }

    private View getView() {
        LayoutInflater inflater = LayoutInflater.from(this);
        return inflater.inflate(R.layout.item_add_layout, null);
    }

    private void addView(View layout) {
        llView.addView(layout);
    }

    private void removeView(View layout) {
        llView.removeView(layout);
    }

    private boolean isPre() {
        for (int i = 0; i < llView.getChildCount(); i++) {
            View view = llView.getChildAt(i);
            EditText etText = (EditText) view.findViewById(R.id.et_text);
            ImageView ivPic = (ImageView) view.findViewById(R.id.iv_pic);
            String trim = etText.getText().toString().trim();
            String tag =(String)ivPic.getTag();
            if (!(!TextUtils.isEmpty(trim) && !TextUtils.isEmpty(tag))) {
                ToastUtils.showShortToastSafe("请填写步骤说明并且上传示例图片");
                return false;
            }
        }
        return true;
    }

    private void refreshType(boolean isSelected) {
        if (isSelected) {
            opentype = "1";
            //选择二维码
            tvEcode.setSelected(true);
            tvLianjie.setSelected(false);
            tvEcode.setTextColor(getResources().getColor(R.color.white));
            tvLianjie.setTextColor(getResources().getColor(R.color.maincolor));

            ivPic.setVisibility(View.VISIBLE);
            etLianjie.setVisibility(View.GONE);
        } else {
            opentype = "2";
            //选择链接
            tvEcode.setSelected(false);
            tvLianjie.setSelected(true);
            tvEcode.setTextColor(getResources().getColor(R.color.maincolor));
            tvLianjie.setTextColor(getResources().getColor(R.color.white));

            ivPic.setVisibility(View.GONE);
            etLianjie.setVisibility(View.VISIBLE);
        }

        ivPic.setOnClickListener(v -> {
            ImagePicker.getInstance().setSelectLimit(1);
            ImagePicker.getInstance().setCrop(false);
            ImagePicker.getInstance().setShowCamera(true);
            ImagePicker.getInstance().setMultiMode(true);
            Intent intent1 = new Intent(context, ImageGridActivity.class);
            startActivityForResult(intent1, 110);
        });


    }

    private double danjia = 0;
    private int shuliang = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    class TextWatch implements TextWatcher {

        private int WatchNum;


        public TextWatch(int num) {
            WatchNum = num;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (WatchNum == 1) {
                if (charSequence.length() > 0) {
                    try {
                        String danjiaStr = charSequence.toString();
                        danjia = Double.valueOf(danjiaStr);
                    } catch (Exception e) {
                        danjia = 0;
                    }

                } else {
                    danjia = 0;
                }
            }

            if (WatchNum == 2) {
                if (charSequence.length() > 0) {
                    try {
                        String shuliangStr = charSequence.toString();
                        shuliang = Integer.parseInt(shuliangStr);
                    } catch (Exception e) {
                        shuliang = 0;
                    }
                } else {
                    shuliang = 0;
                }
            }
            changTotalAndNeed();
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    }

    /**
     * 修改总价
     */
    private void changTotalAndNeed() {
        if (ckZhiding.isSelected()) {
            zhidingNum = shuliang * 2;
        } else {
            zhidingNum = 0;
        }
        double total = danjia * shuliang + zhidingNum;
        tvTotal.setText(String.format("%s", total));
        if (total < money) {
            tvNeedChongzhi.setText("0");
        } else {
            tvNeedChongzhi.setText(String.format("%s", ComUtils.sub(total, money)));
        }
    }

    /**
     * 获取余额
     */
    private void getMoney() {
        showProgress();
        userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);
        userPresenter.moneyView(userid, ConstantValue.RequestKey.getMoneyView);
    }

    private List<BuzhouEntity> students = new ArrayList<>();

    @OnClick({R.id.iv_back, R.id.ll_zhiding, R.id.rl_task_type, R.id.tv_ecode, R.id.tv_lianjie, R.id.tv_chongzhi, R.id.tv_fabu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_task_type:
                //选择类型
                if (!isGuanfang) {
                    showTaskTypeDialog();
                }
                break;
            case R.id.tv_chongzhi:
                //充值
                startActivity(new Intent(context, ChongZhiActivity.class));
                break;
            case R.id.ll_zhiding:
                //是否置顶
                setZhiding(iszhiding);
                break;
            case R.id.tv_ecode:
                refreshType(true);
                break;
            case R.id.tv_lianjie:
                refreshType(false);
                break;
            case R.id.tv_fabu:
                if (AppUtils.isFastClick()) {
                    ToastUtils.showShortToastSafe("操作有点频繁,稍后重试");
                    return;
                }
                if (isPre()) {
                    if (students.size() > 0) {
                        students.clear();
                    }
                    for (int i = 0; i < llView.getChildCount(); i++) {
                        View view1 = llView.getChildAt(i);
                        EditText etText = (EditText) view1.findViewById(R.id.et_text);
                        ImageView ivPic = (ImageView) view1.findViewById(R.id.iv_pic);
                        CheckBox cbCheck = (CheckBox) view1.findViewById(R.id.cb_check);
                        BuzhouEntity student = new BuzhouEntity();
                        student.setStep_text(etText.getText().toString().trim());
                        student.setStep_pic("" + ivPic.getTag());
                        student.setFlag(cbCheck.isChecked() ? "1" : "0");
                        students.add(student);
                    }
                    String jsonStr = new Gson().toJson(students);
                    Logger.e("xuke", "json = " + jsonStr);
                    step = jsonStr;
                    //发布
                    if (!TextUtils.isEmpty(jsonStr)) {
                        PushDialog instance = PushDialog.getInstance(String.valueOf(c_id));
                        instance.show(getSupportFragmentManager(), "pushdialog");
                        instance.setClickCallback(new PushDialog.OnClickCallback() {
                            @Override
                            public void cancel() {
                                instance.dismiss();
                            }

                            @Override
                            public void confirm() {
                                instance.dismiss();
                                fabu("");
                            }
                        });
                    } else {
                        ToastUtils.showShortToastSafe("请填写操作步骤");
                    }
                }
                break;
        }
    }

    private void setZhiding(boolean iszhiding) {
        ckZhiding.setSelected(this.iszhiding);
        this.iszhiding = !iszhiding;
        changTotalAndNeed();
    }

    /**
     * 准备发布
     */
    private boolean isPer() {
        if (selImageList.size() == 0) {
            ToastUtils.showShortToastSafe("请添加示例图片");
            return false;
        }
        return true;
    }

    /**
     * 发布
     */
    private void fabu(String images) {
        String userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);
        if (mData != null && mData.size() > 0) {
            CateListEntity.CatelistBean catelistBean = mData.get(typePostion);
            c_id = catelistBean.getC_id();
        } else {
            c_id = 10010;
        }

        if (isGuanfang) {
            c_id = 2;
        }

        double money = this.danjia;
        int shuliang = this.shuliang;

        String taskname = etTaskName.getText().toString().trim();
        String text = etInfo.getText().toString().trim();

        if ("1".equals(opentype)) {
            openurl = imageurl;
        } else {
            openurl = etLianjie.getText().toString().trim();
        }

        if (c_id == 10010){
            ToastUtils.showShortToastSafe("请先选择任务类型");
            return;
        }

        if (TextUtils.isEmpty(openurl)) {
            ToastUtils.showShortToastSafe("请先选择任务打开方式并上传相关二维码或者链接");
            return;
        }

        if (TextUtils.isEmpty(taskname)) {
            ToastUtils.showShortToastSafe("任务名称必填");
            return;
        }

        showProgress();
        taskPresenter.pushTask3(t_id,userid, c_id, taskname, money, shuliang, ckZhiding.isSelected(),
                text, opentype, openurl, step, ConstantValue.RequestKey.push_task);
    }

    /**
     * 获取发布类型
     */
    private void showTaskTypeDialog() {
        showProgress();
        taskPresenter.getCatelist(ConstantValue.RequestKey.task_type);
    }
    private void getTaskType()
    {
        taskPresenter.getCatelist(ConstantValue.RequestKey.task_type_show);
    }
    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                pickImage();
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    private void pickImage() {
        //打开选择,本次允许选择的数量
        ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
        ImagePicker.getInstance().setCrop(false);
        ImagePicker.getInstance().setShowCamera(true);
        ImagePicker.getInstance().setMultiMode(true);
        Intent intent1 = new Intent(context, ImageGridActivity.class);
        startActivityForResult(intent1, REQUEST_CODE_SELECT);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        }

        //二维码添加返回
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 110) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    showProgress();
                    appPresenter.upload3(new File(images.get(0).getPath()), "uploadfile");
                }
            }
        }


        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == 1110) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    image = xkview.findViewById(R.id.iv_pic);
                    Logger.e("xuke", "--->" + images.get(0));
                    showProgress();
                    appPresenter.upload3(new File(images.get(0).getPath()), "step");

                }
            }
        }
    }


    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        dismissProgress();
        if (ConstantValue.RequestKey.getMoneyView.equals(actionType)) {
            //获取用户余额
            MoneyEntity.UserBean userBean = (MoneyEntity.UserBean) data;
            money = userBean.getMoney();
        }

        if (ConstantValue.RequestKey.task_type_show.equals(actionType)) {
            List<CateListEntity.CatelistBean> catelist = (List<CateListEntity.CatelistBean>) data;

            if (catelist != null && catelist.size() > 0) {
                mData.clear();
                mData.addAll(catelist);
            }
            //设置默认值
            tvTypeTitle.setText(mData.get(0).getCatename());
            c_id=mData.get(0).getC_id();
        }
        if (ConstantValue.RequestKey.task_type.equals(actionType)) {
            List<CateListEntity.CatelistBean> catelist = (List<CateListEntity.CatelistBean>) data;

            if (catelist != null && catelist.size() > 0) {
                mData.clear();
                mData.addAll(catelist);
            }

            TaskTypeDialog bottomDialog = TaskTypeDialog.getInstance(mData);
            bottomDialog.show(getSupportFragmentManager(), "task_type");
            bottomDialog.setClickCallback(new TaskTypeDialog.OnClickCallback() {
                @Override
                public void onItemClick(int position) {
                    bottomDialog.dismiss();
                    typePostion = position;
                    CateListEntity.CatelistBean catelistBean = mData.get(position);
                    tvTypeTitle.setText(catelistBean.getCatename());
                    c_id=catelistBean.getC_id();
                }

                @Override
                public void cancel() {
                    bottomDialog.dismiss();
                }
            });
        }

        if (ConstantValue.RequestKey.push_task.equals(actionType)) {
            ToastUtils.showShortToastSafe("发布任务成功,等待后台审核");
            finish();
        }

        if ("uploadfile".equals(actionType)) {
            String url = (String) data;
            imageurl = url;
            if (ivPic != null) {
                ImageLoader.displayImage(this, ConstantValue.IMG_BASEURL + url, ivPic);
            }
        }

        if ("step".equals(actionType)) {
            String url = (String) data;
            if (image != null && !url.equals(image.getTag())) {
                image.setTag("");
                ImageLoader.displayImage(this, ConstantValue.IMG_BASEURL + url, image);
                image.setTag(url);
            }

        }


    }

    @Override
    public void onFailed(String code, String msg) {
        dismissProgress();
        ToastUtils.showShortToastSafe(msg);
    }

    @Override
    protected void onDestroy() {
        if (image != null) {
            image.setTag("");
        }

        if (llView != null) {
            for (int i = 0; i < llView.getChildCount(); i++) {
                View view = llView.getChildAt(i);
                ImageView ivPic = (ImageView) view.findViewById(R.id.iv_pic);
                ivPic.setTag("");
            }
        }
        super.onDestroy();
    }


}
